/**
 * XML Parser that uses SAX to parse the XML Response
 * 
 **/
package com.syde322;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.SAXException;

import com.syde322.WikiFacts;
import com.syde322.FactsHandler;


public class XmlParser {
	
	 private XMLReader initializeReader() throws ParserConfigurationException, SAXException {
		         SAXParserFactory factory = SAXParserFactory.newInstance();
		         // create a parser
		         SAXParser parser = factory.newSAXParser();
		         //interface for reading XML document using callbacks
		         XMLReader xmlreader = parser.getXMLReader();
		         return xmlreader;
		     }

	 public ArrayList<WikiFacts> parseFacts(String xml) {
	        
	        try {            
	            XMLReader xmlreader = initializeReader();	            
	            FactsHandler factsHandler = new FactsHandler();
	            xmlreader.setContentHandler(factsHandler);
	            // perform the synchronous parse
	            xmlreader.parse(new InputSource(new StringReader(xml)));
	            
	            return FactsHandler.retrieveFactsList();	            
	        } 
	        catch (Exception e) {
	            e.printStackTrace();
	            return null;
	        }
	        
	    }
	    
}
